package stardust.core.support.js;


import java.util.Iterator;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


public class JavaScriptExecuteor
{

  private ScriptEngineManager scriptEngineManager;

  private ScriptEngine scriptEngine;

  private ScriptContext ctx;

  public JavaScriptExecuteor(String script) throws ScriptException
  {
    this.scriptEngineManager = new ScriptEngineManager();
    this.scriptEngine = this.scriptEngineManager.getEngineByName("javascript");
    this.ctx = this.scriptEngine.getContext();

    this.scriptEngine.eval(script);
  }

  public void initialize(Map<String, Object> param) throws ScriptException
  {
    if (param != null)
    {
      Iterator<String> key = param.keySet().iterator();
      String k;

      while (key.hasNext())
      {
        k = key.next();
        ctx.setAttribute(k, param.get(k), ScriptContext.ENGINE_SCOPE);
      }
    }
  }

  public Object execute(String func, Object... args) throws ScriptException, NoSuchMethodException
  {
    Invocable ivk;

    ivk = (Invocable) this.scriptEngine;

    return ivk.invokeFunction(func, args);
  }

}
